//
//  FLRequest.m
//  Cat
//
//  Created by lushitong on 2018/12/1.
//  Copyright © 2018年 lushitong. All rights reserved.
//

#import "FLRequest.h"
#import "AFNetworking.h"
#import "NSDictionary+FLRequest.h"
#import "FLHttpParser.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "FLTool.h"

@implementation FLRequest

static BOOL _isOpenLog;   // 是否已开启日志打印
static NSMutableArray *_allSessionTask;
static AFHTTPSessionManager *_sessionManager;

+ (NSURLSessionTask *)GET:(NSString *)URL parameters:(id)parameters success:(FLSuccess)success failure:(nonnull FLFailure)failure {
	
	DDLogDebug(@"\n============ Http response success ============\nURL:%@\n%@\n", URL, parameters);
	NSDictionary *encodeParams = [NSDictionary encodeRequestPararms:parameters];
	
	if (UDToken) {
		[_sessionManager.requestSerializer setValue:UDToken forHTTPHeaderField:@"auth-token"];
	}
	
	NSURLSessionTask *sessionTask = [_sessionManager GET:URL parameters:encodeParams progress:^(NSProgress * _Nonnull downloadProgress) {
		
	} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
		[[self allSessionTask] removeObject:task];
		NSInteger rc = [FLHttpParser rcValueOfResponse:responseObject];
		
		NSDictionary *decodeDict = [NSDictionary decodeRequestResult:responseObject];
		
		if (_isOpenLog) {
			DDLogDebug(@"\n============ Http response success ============\nURL:%@\n%@\n", URL, decodeDict);
		}
		
		if (rc == 99) {
			if (success) {
				success([FLHttpParser dataDictOfResponse:decodeDict]);
			}
		} else if (rc == 1002) {
			UDToken = @"";
			failure(rc,[FLHttpParser messageOfResponse:decodeDict]);
		} else {
			failure(rc,[FLHttpParser messageOfResponse:decodeDict]);
		}
	} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
		if (_isOpenLog) {QKLog(@"error  = %@",error);}
		[[self allSessionTask] removeObject:task];
		failure ? failure(-9999, (error.code == -1009)? @"请检查您的手机网络是否正常" : @"服务器好像在开小差") : nil;
	}];
	
	sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil;
	return sessionTask;
}

+ (NSURLSessionTask *)POST:(NSString *)URL parameters:(id)parameters success:(nonnull FLSuccess)success failure:(nonnull FLFailure)failure {
	
	DDLogDebug(@"\n============ Http response success ============\nURL:%@\n%@\n", URL, parameters);
	
	NSMutableDictionary *fullParams = [self requestParamsAddVersion:parameters];
	// 加密
	NSDictionary *encodeParams = [NSDictionary encodeRequestPararms:fullParams];
	
	if (UDToken) {
		[_sessionManager.requestSerializer setValue:UDToken forHTTPHeaderField:@"auth-token"];
	}
	
	NSURLSessionTask *sessionTask =[_sessionManager POST:URL parameters:encodeParams progress:^(NSProgress * _Nonnull uploadProgress) {
		
	} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
		if (_isOpenLog) {QKLog(@"responseObject  = %@",responseObject);}
		[[self allSessionTask] removeObject:task];
		NSInteger rc = [FLHttpParser rcValueOfResponse:responseObject];
		NSDictionary *decodeDict = [NSDictionary decodeRequestResult:responseObject];
		if (_isOpenLog) {DDLogDebug(@"\n============ Http response success ============\nURL:%@\n%@\n", URL, decodeDict);}
		
		if (rc == 99) {
			if (success) {success([FLHttpParser dataDictOfResponse:decodeDict]);}
		} else if (rc == 1002) {
			UDToken = @"";
			failure(rc,[FLHttpParser messageOfResponse:decodeDict]);
		} else {
			failure(rc,[FLHttpParser messageOfResponse:decodeDict]);
		}
		
	} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
		if (_isOpenLog) {QKLog(@"error  = %@",error);}
		[[self allSessionTask] removeObject:task];
		failure ? failure(-9999, (error.code == -1009)? @"请检查您的手机网络是否正常" : @"服务器好像在开小差") : nil;
	}];
	
	sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil;
	return sessionTask;
}

+ (NSURLSessionTask *)uploadFileWithURL:(NSString *)URL
							   andImage:(UIImage *)image
							   progress:(FLProgress)progress
								success:(FLSuccess)success
								failure:(FLFailure)failure {
	
	NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
		NSError *error = nil;
		NSData *imgData = UIImageJPEGRepresentation(image, 0.4);
		[formData appendPartWithFileData:imgData name:@"file" fileName:@"avatar.png" mimeType:@"image/png"];
		failure ? failure(-9999, (error.code == -1009)? @"请检查您的手机网络是否正常" : @"服务器好像在开小差") : nil;
	} progress:^(NSProgress * _Nonnull uploadProgress) {
		//上传进度
		dispatch_sync(dispatch_get_main_queue(), ^{
			progress ? progress(uploadProgress) : nil;
		});
	} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
		if (_isOpenLog) {QKLog(@"responseObject  = %@",responseObject);}
		[[self allSessionTask] removeObject:task];
		NSInteger rc = [FLHttpParser rcValueOfResponse:responseObject];
		NSDictionary *decodeDict = [NSDictionary decodeRequestResult:responseObject];
		if (_isOpenLog) {QKLog(@"\n============ Http response success ============\nURL:%@\n%@\n", URL, decodeDict);}
		
		if (rc == 99) {
			if (success) {success([FLHttpParser dataDictOfResponse:decodeDict]);}
		} else if (rc == 1002) {
			UDToken = @"";
		} else {
			failure(rc,[FLHttpParser messageOfResponse:decodeDict]);
		}
	} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
		if (_isOpenLog) {QKLog(@"error  = %@",error);}
		[[self allSessionTask] removeObject:task];
		failure ? failure(-9999, (error.code == -1009)? @"请检查您的手机网络是否正常" : @"服务器好像在开小差") : nil;
	}];
	
	// 添加sessionTask到数组
	sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
	
	return sessionTask;
}

#pragma mark----- 处理的方法 -----

+ (void)openLog {
	_isOpenLog = YES;
}

+ (void)closeLog {
	_isOpenLog = NO;
}

+ (void)cancelRequestWithURL:(NSString *)URL {
	if (!URL) { return; }
	@synchronized (self) {
		[[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
			if ([task.currentRequest.URL.absoluteString hasPrefix:URL]) {
				[task cancel];
				[[self allSessionTask] removeObject:task];
				*stop = YES;
			}
		}];
	}
}
/**
 存储着所有的请求task数组
 */

+ (NSMutableArray *)allSessionTask {
	if (!_allSessionTask) {
		_allSessionTask = [[NSMutableArray alloc] init];
	}
	return _allSessionTask;
}

#pragma mark----- 公共参数 -----

+ (NSMutableDictionary *)requestParamsAddVersion:(NSDictionary *)params {
	NSMutableDictionary *dict = params ? [NSMutableDictionary dictionaryWithDictionary:params] : [NSMutableDictionary dictionary];
	return dict;
}

#pragma mark----- 初始化方法 -----

+ (void)load {
	[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

+ (void)initialize {
	_sessionManager = [AFHTTPSessionManager manager];
	_sessionManager.requestSerializer.timeoutInterval = 30.f;
	_sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*", nil];
	// 打开状态栏的等待菊花
	_sessionManager.requestSerializer =  [AFJSONRequestSerializer serializer];
	_sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
	[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
}


@end
